import { PayloadAction, createSlice } from '@reduxjs/toolkit'
import { UserResponse } from '../User'

type UserWithoutConfirm = Omit<UserResponse, 'confirm'>
export interface UserState {
  avatar?: string
  email: string
  id: string
  lastname: string
  name: string
  occupation: string
}

const initialState: UserState = {
  avatar: '',
  email: '',
  id: '',
  lastname: '',
  name: '',
  occupation: '',
}

const userSlice = createSlice({
  initialState,
  name: 'user',
  reducers: {
    logout: () => initialState,

    setUser(state, action: PayloadAction<UserWithoutConfirm>) {
      const { avatar, email, id, lastname, name, occupation } = action.payload
      state.email = email
      state.id = id
      state.name = name
      state.lastname = lastname || ''
      state.occupation = occupation || ''
      state.avatar = avatar || ''
    },
  },
})

export const { logout, setUser } = userSlice.actions
export const UserReducer = userSlice.reducer
